import { _decorator, Component, Node, Prefab, Label, SpriteAtlas, AudioClip, Vec2, instantiate, Pool, NodePool, Vec3, Tween, director, Color, PhysicsSystem, tween, Sprite, UITransform, RenderComponent, UIOpacity } from 'cc';
import { Hero } from './hero';
import { AudioSource } from '../../extensions/plugin-import-2x/creator/components/AudioSource';
import { Block } from './block';
import { TxDian } from './txDian';
import { Item } from './item';
const { ccclass, property } = _decorator;

@ccclass('Game')
export class Game extends Component {
    @property(Node)
    public bg = null;
    @property(Node)
    public nodeReady = null;
    @property(Node)
    public nodePlay = null;
    @property(Node)
    public nodePHB = null;
    @property(Node)
    public nodeOver = null;
    @property(Node)
    public itemParent = null;
    @property(Prefab)
    public pre_item = null;
    @property(Prefab)
    public pre_block = null;
    @property(Node)
    public hero = null;
    @property(Node)
    public hero_2 = null;
    @property(Label)
    public lab_score = null;
    @property(Label)
    public lab_currScoreOver = null;
    @property(Label)
    public lab_bestScoreOver = null;
    @property(Node)
    public phOver = null;
    @property(SpriteAtlas)
    public spa_touXiang = null;
    @property(Label)
    public tx_score = null;
    @property(Node)
    public tx_guangQuan = null;
    @property(Prefab)
    public pre_dian = null;
    @property(AudioClip)
    public audio_score_1 = null;
    @property(AudioClip)
    public audio_score_2 = null;
    @property(AudioClip)
    public audio_fall = null;
    @property(AudioClip)
    public audio_touch_1 = null;
    @property(AudioClip)
    public audio_touch_2 = null;

    public static instance: Game;
    private blockPool: NodePool;
    private callBackHeroJump: Function | null = null;
    private callBackGetScore: Function;
    private dianPool: NodePool;
    private doubleScore: number = 1;
    private isTouchStart: boolean = false;
    private currScore: number = 0;
    private timeTouch: number = 0;
    private isTouchBegin: boolean = false;
    public gameType: number = 0;
    public isGetScore: number = -1;
    // arrColorBg: Color[] = [
    //     new Color(191, 192, 201),
    //     new Color(244, 220, 216),
    //     new Color(198, 224, 211),
    //     new Color(242, 215, 171),
    //     new Color(165, 191, 216),
    //     new Color(231, 219, 222)
    // ];
    arrColorBg = [
        { r: 191, g: 192, b: 201 },
        { r: 244, g: 220, b: 216 },
        { r: 198, g: 224, b: 211 },
        { r: 242, g: 215, b: 171 },
        { r: 165, g: 191, b: 216 },
        { r: 231, g: 219, b: 222 },
    ]
    arr_infor = [
        { name: '2504549300', touXiang: 0, score: 1003 },
        { name: 'cocoscreator_666', touXiang: 1, score: 1002 },
        { name: '我', touXiang: 2, score: 1001 },
        { name: '褪了色旳回憶', touXiang: 3, score: Math.round(Math.random() * 1000) },
        { name: '为爱控', touXiang: 4, score: Math.round(Math.random() * 1000) },
        { name: '等尽歌悲欢', touXiang: 5, score: Math.round(Math.random() * 1000) },
        { name: '妖媚＠', touXiang: 6, score: Math.round(Math.random() * 1000) },
        { name: '时光あ瘦了~', touXiang: 7, score: Math.round(Math.random() * 1000) },
        { name: '别格式化', touXiang: 8, score: Math.round(Math.random() * 1000) },
        { name: '同餐伴枕', touXiang: 9, score: Math.round(Math.random() * 1000) },
    ]

    onLoad() {
        // console.log('qq:2504549300') 
        // console.log('微信:cocoscreator_666') 
        (window as any).game = this;
        this.nodeReady.active = true;
        this.nodePlay.active = false;
        this.nodePHB.active = false;
        this.nodeOver.active = false;
        this.nodeReady.setSiblingIndex(9);
        this.nodeOver.setSiblingIndex(9);
        this.nodePHB.setSiblingIndex(10);
        this.setInfor();
        this.setTouch();
        this.gameType = 0;//0:Ready  1:play 2:over 
        this.blockPool = new NodePool();
        this.dianPool = new NodePool();
        this.hero.active = false;
        this.tx_score.node.getComponent(UIOpacity).opacity = 0;
        this.tx_guangQuan.getComponent(UIOpacity).opacity = 0;
        this.tx_guangQuan.setSiblingIndex(10);
        const physicsSystem = PhysicsSystem.instance;
        physicsSystem.enable = true;
        this.bg.color = new Color(this.arrColorBg[0].r, this.arrColorBg[0].b, this.arrColorBg[0].g)
        this.setReady();
    }

    constructor() {
        super();
        Game.instance = this; // 确保静态属性 instance 指向当前 Game 实例
    }

    //增加分数
    addScore(num: any) {
        if (this.callBackGetScore) {
            this.unschedule(this.callBackGetScore);
        }
        var addScore = num;
        if (num == 2) {
            this.doubleScore = this.doubleScore * 2
            addScore = this.doubleScore;
            //cc.audioEngine.play(this.audio_score_2, false, 1);
            //AudioSource.play(this.audio_score_2, { loop: false, volume: 1 }); 
            //this.audio_score_2.play(); //播放声音，暂时跳过
        } else if (num == 1) {
            this.doubleScore = 1;
            //cc.audioEngine.play(this.audio_score_1, false, 1);
        }
        if (num == 1 || num == 2) {
            if (Math.random() < 0.1) {
                this.setRandomBgColor();
            }
            var numDian = 5 + Math.floor(Math.random() * 7);
            for (let i = 0; i < numDian; i++) {
                this.createDian(this.hero.getPosition(), 'end');
            }
        }
        this.tx_score.string = '+' + addScore;
        this.tx_score.node.opacity = 255;
        this.tx_score.node.setPosition(new Vec3(this.hero.x, this.hero.position.y + 100));
        // var act_1 = cc.moveBy(1, cc.v2(0, 100))
        // var act_2 = cc.fadeOut(1)
        // var end = cc.spawn(act_1, act_2)
        // this.tx_score.node.runAction(end)
        const act_1 = { position: new Vec3(0, 100, 0) };
        const act_2 = { opacity: 0 };
        tween(this.tx_score.node)
            .by(1, act_1)
            .to(1, act_2)
            .start();

        this.currScore += addScore;
        this.lab_score.string = this.currScore;
        if (num == 2) {
            this.tx_guangQuan.setPosition(new Vec3(this.hero.x, this.hero.position.y + 20));
            this.tx_guangQuan.opacity = 255;
            // this.tx_guangQuan.scale = 1
            // var act_01 = cc.scaleTo(0.5, 5, 2)
            // var act_02 = cc.fadeOut(0.5)
            // var end_1 = cc.spawn(act_01, act_02)
            // this.tx_guangQuan.runAction(end_1)
            this.tx_guangQuan.scale = new Vec3(1, 1, 1);
            const act_01 = { scale: new Vec3(5, 2, 1) };
            const act_02 = { opacity: 0 };
            tween(this.tx_guangQuan)
                .to(0.5, act_01)
                .to(0.5, act_02)
                .start();
        }
    }

    //判断得分方块类型
    txBlock() {
        var children = this.node.children;
        var i_num = 0;
        for (let i = children.length - 1; i >= 0; i--) {
            var js = children[i].getComponent(Block);
            if (js) {
                i_num++
                if (i_num == 2 && js.blockType > 18) {
                    this.callBackGetScore = function () {
                        if (this.gameType != 1) return
                        if (children[i].getComponent(Block).blockType == 19) {
                            this.addScore(5);
                        } else if (children[i].getComponent(Block).blockType == 20) {
                            this.addScore(8);
                        } else if (children[i].getComponent(Block).blockType == 21) {
                            this.addScore(10);
                        }
                        children[i].getComponent(Block).playAnima();
                    }
                    this.scheduleOnce(this.callBackGetScore, 3);
                }
            }
        }
    }

    //创建方块
    createBlock(pos_dian: any, blockType: any, isFirst: any) {
        let block = null;
        if (this.blockPool.size() > 0) { // 通过 size 接口判断对象池中是否有空闲的对象 
            block = this.blockPool.get();
        } else { // 如果没有空闲对象，也就是对象池中备用对象不够时，我们就用 instantiate 重新创建 
            block = instantiate(this.pre_block);
        }
        block.parent = this.node.getChildByName("block"); // 将生成的敌人加入节点树
        block.getComponent(Block).init(pos_dian, blockType, isFirst);
    }

    //杀死不需要的方块（将其放入对象池）
    onBlockKilled(block: any) {
        this.blockPool.put(block); // 和初始化时的方法一样，将节点放进对象池，这个方法会同时调用节点的 removeFromParent 
    }

    //创建节点
    createDian(pos: any, touchType: any) {
        let dian = null;
        if (this.dianPool.size() > 0) { // 通过 size 接口判断对象池中是否有空闲的对象 
            dian = this.dianPool.get();
        } else { // 如果没有空闲对象，也就是对象池中备用对象不够时，我们就用 cc.instantiate 重新创建 
            dian = instantiate(this.pre_dian);
        }
        dian.parent = this.node; // 将生成的敌人加入节点树 
        if (touchType == 'start') {
            dian.setSiblingIndex(2);
            dian.getComponent(TxDian).init_1(pos);
        } else if (touchType == 'end') {
            dian.setSiblingIndex(3);
            dian.getComponent(TxDian).init_2(pos);
        }
    }

    //清理所有Tx点
    cleanAllTXDian() {
        var children = this.node.children
        for (let i = children.length - 1; i >= 0; i--) {
            var js = children[i].getComponent(TxDian)
            if (js) {
                this.onDianKilled(children[i])
            }
        }
    }

    //杀死不需要的Tx点（将其放入对象池）
    onDianKilled(dian: any) {
        this.dianPool.put(dian); // 和初始化时的方法一样，将节点放进对象池，这个方法会同时调用节点的 removeFromParent 
    }

    //计算创建方块数据并创建方块
    pdDir() {
        var arr_pos = [];
        var children = this.node.getChildByName("block").children;
        for (let i = children.length - 1; i >= 0; i--) {
            var js = children[i].getComponent(Block);
            if (js) {
                arr_pos.push(js.pos_dianWorld as Vec3);
            }
        }
        var pos_1 = arr_pos[0].subtract(arr_pos[1]).normalize();// 计算第一个坐标与第二个坐标之间的单位方向向量（归一化）。
        var f_random = 290 + Math.random() * 160;// 生成随机距离
        if (Math.random() * 10 < 5) {
            pos_1.x = pos_1.x * -1;
        }
        var pos_end = new Vec3(arr_pos[0].x + pos_1.x * f_random, arr_pos[0].y + pos_1.y * f_random);
        var numRandom = Math.floor(Math.random() * 22);
        this.createBlock(pos_end, numRandom, 3);
    }

    //移动
    moveDir() {
        var arr_pos = [];
        var children = this.node.getChildByName("block").children;
        for (let i = children.length - 1; i >= 0; i--) {
            var js = children[i].getComponent(Block);
            if (js) {
                arr_pos.push(js.pos_dianWorld);
            }
        }
        var pos_cha = new Vec3((arr_pos[0].x - arr_pos[1].x) / 2, (arr_pos[0].y - arr_pos[1].y) / 2);
        var pos_move = new Vec3(0 - (arr_pos[1].x + pos_cha.x), -150 - (arr_pos[1].y + pos_cha.y));
        for (let i = children.length - 1; i >= 0; i--) {
            var js = children[i].getComponent(Block);
            if (js) {
                js.canTouch = false;
                const act_1 = { position: new Vec3(pos_move.x, pos_move.y, 0) };
                const act_2 = () => {
                    children[i].getComponent(Block).setDianPos();
                };
                tween(children[i])
                    .by(0.5, act_1)
                    .call(act_2)
                    .start();
            }
        }
        const act_1 = { position: new Vec3(pos_move.x, pos_move.y, 0) };
        tween(this.hero)
            .by(0.5, act_1)
            .start();
        tween(this.tx_score.node)
            .by(0.5, act_1)
            .start();
        this.txBlock();
        console.log(children.length);
    }

    //触摸
    canTouch() {
        var children = this.node.getChildByName("block").children;
        for (let i = children.length - 1; i >= 0; i--) {
            var js = children[i].getComponent(Block);
            if (js) {
                if (js.canTouch == false) {
                    return false;
                }
            }
        }
        return true;
    }

    //清理方块
    cleanBlock() {
        var children = this.node.getChildByName("block").children;
        for (let i = children.length - 1; i >= 0; i--) {
            var js = children[i].getComponent(Block);
            if (js) {
                if (js.pos_dianWorld.y < -900) {
                    this.onBlockKilled(children[i]);
                }
            }
        }
    }

    //设置触摸
    setTouch() {
        this.node.on('touchstart', function (event) {
            if (this.gameType != 1) return;
            if (this.canTouch() == false) return;
            if (this.hero.getComponent(Hero).canTouch == false) return;
            this.isTouchStart = true;
            this.isGetScore = -1;
            this.hero.eulerAngles.z = 0;
            this.hero_2.active = false;
            this.isTouchBegin = true;
            this.timeTouch = 0;
            //this.audioTouch_1 = cc.audioEngine.play(this.audio_touch_1, false, 1)
            this.callBackTouch_2 = function () {
                //this.audioTouch_2 = cc.audioEngine.play(this.audio_touch_2, true, 1)
            }
            //this.scheduleOnce(this.callBackTouch_2, cc.audioEngine.getDuration(this.audioTouch_1))// 声音，稍后改
            var numDian = 3 + Math.floor(Math.random() * 7);
            for (let i = 0; i < numDian; i++) {
                this.createDian(this.hero.getPosition(), 'start');
            }
            this.callBacktxDian = function () {
                var numDian = 3 + Math.floor(Math.random() * 7);
                for (let i = 0; i < numDian; i++) {
                    this.createDian(this.hero.getPosition(), 'start');
                }
            }
            this.schedule(this.callBacktxDian, 0.5);
            console.log('touchstart');
        }, this)
        this.node.on('touchmove', function (event) {
            if (this.gameType != 1) return;
            console.log('touchmove');
        }, this)
        this.node.on('touchend', function (event) {
            if (this.isTouchStart == false) return;
            if (this.gameType != 1) return;
            if (this.canTouch() == false) return;
            if (this.hero.getComponent(Hero).canTouch == false) return;
            this.isTouchStart = false;
            this.isTouchBegin = false;
            //cc.audioEngine.stop(this.audioTouch_1);
            //cc.audioEngine.stop(this.audioTouch_2);// 声音部分，稍后改
            if (this.callBackTouch_2) {
                this.unschedule(this.callBackTouch_2);
            }
            this.cleanAllTXDian();
            this.unschedule(this.callBacktxDian);
            var pos_blockEnd = new Vec3(0, 0);
            var numnum = 0;
            var children = this.node.getChildByName("block").children;
            for (let i = children.length - 1; i >= 0; i--) {
                var js = children[i].getComponent(Block);
                if (js) {
                    numnum++;
                    if (numnum == 2) {
                        js.touchEnd();
                    } else if (numnum == 1) {
                        pos_blockEnd = js.pos_dianWorld;
                    }
                }
            }
            var pos_hero = this.hero.getPosition()
            var pos_1 = pos_blockEnd.subtract(pos_hero).normalize();
            var timeDir = this.timeTouch * 8;
            var pos_end = new Vec3(pos_hero.x + pos_1.x * timeDir, pos_hero.y + pos_1.y * timeDir + this.hero.getComponent(UITransform).height / 2);
            // var act_0 = callFunc(function () {
            //     this.hero.getComponent('hero').canTouch = false
            //     this.hero.anchorY = 0.5
            //     this.hero.y = this.hero.y + this.hero.height / 2
            // }.bind(this))
            const act_0 = () => {
                this.hero.getComponent(Hero).canTouch = false;
                this.hero.getComponent(UITransform).anchorY = 0.5;
                this.hero.position = new Vec3(this.hero.position.x,this.hero.position.y + this.hero.getComponent(UITransform).height / 2);
            };
            // var act_1 = cc.jumpTo(0.4, pos_end, 200, 1)
            // var act_2 = cc.rotateBy(0.4, 360)
            // var act_3 = cc.rotateBy(0.4, -360)
            var act_1 = tween(this.hero)
                .to(0.4, {
                    position: new Vec3(pos_end.x, pos_end.y, pos_end.z), // 移动到目标位置
                    easing: 'sineInOut' // 使用合适的缓动函数模拟平滑运动
                });

            // 2. 用 tween 来替代 rotateBy 动画（顺时针旋转）
            var act_2 = tween(this.hero)
                .to(0.4, {
                    rotation: this.hero.eulerAngles.z + 360 // 顺时针旋转 360°
                });

            // 3. 用 tween 来替代 rotateBy 动画（逆时针旋转）
            var act_3 = tween(this.hero)
                .to(0.4, {
                    rotation: this.hero.eulerAngles.z - 360 // 逆时针旋转 360°
                });
            var act_4 = () => {
                this.hero.getComponent(UITransform).anchorY = 0
                this.hero.position = new Vec3(this.hero.position.x,this.hero.position.y - this.hero.getComponent(UITransform).height / 2);
                this.hero_2.active = true
                this.scheduleOnce(function () {
                    if (this.isGetScore == -1) {
                        this.hero_2.active = false
                        console.log('踩空死亡')
                        this.gameType = 2
                        var children = this.node.getChildByName("block").children
                        var arr_num = []
                        for (let i = children.length - 1; i >= 0; i--) {
                            var js = children[i].getComponent(Block)
                            if (js) {
                                arr_num.push(i)
                            }
                        }
                        var pos_end_1 = children[arr_num[0]].getComponent(Block).pos_dianWorld
                        var pos_end_2 = children[arr_num[1]].getComponent(Block).pos_dianWorld
                        var pos_hero = this.hero.getPosition()
                        if (pos_hero.x > pos_end_1.x && pos_hero.x > pos_end_2.x) {
                            children[arr_num[0]].zIndex = 5
                        } else if (pos_hero.x < pos_end_1.x && pos_hero.x < pos_end_2.x) {
                            children[arr_num[0]].zIndex = 5
                        } else {
                            children[arr_num[1]].zIndex = 5
                        }
                        // var act_001 = cc.moveBy(0.5, cc.v2(0, -75))
                        // var act_002 = cc.callFunc(function () {
                        //     this.gameOver()
                        // }.bind(this))
                        // this.hero.runAction(cc.sequence(act_001, act_002))
                        const act_001 = new Tween(this.node)
                            .to(0.5, { position: new Vec3(0, -75, 0) });

                        const act_002 = () => {
                            this.gameOver();
                        };
                        new Tween(this.hero)
                            .then(act_001)
                            .call(act_002)
                            .start();
                    } else if (this.isGetScore == 0) {
                        console.log('滑到死亡')
                    }
                    this.pdCreateBlock()
                    this.hero.getComponent(Hero).canTouch = true
                }, 0.1)
            };
            if (pos_1.x > 0) {
                //var act_5 = cc.spawn(act_1, act_2)
                const act_5 = tween().parallel(act_1, act_2);
                // var end = cc.sequence(act_0, act_5, act_4)
                // this.hero.runAction(end)
                var end = tween(this.hero)
                    .call(act_0) // 先执行 act_1 (跳跃动作)
                    .then(act_5) // 然后执行 act_2 (顺时针旋转)
                    .call(act_4) // 最后执行 act_3 (逆时针旋转)
                    .start();
            } else {
                //var act_6 = cc.spawn(act_1, act_3)
                //同时执行多个动作
                const act_6 = tween().parallel(act_1, act_3);
                // var end = cc.sequence(act_0, act_6, act_4)
                // this.hero.runAction(end)
                //依次执行动作
                var end = tween(this.hero)
                    .call(act_0) // 先执行 act_1 (跳跃动作)
                    .then(act_6) // 然后执行 act_2 (顺时针旋转)
                    .call(act_4) // 最后执行 act_3 (逆时针旋转)
                    .start();
            }
            console.log('touchend')
        }, this)
    }

    //游戏结束
    gameOver() {
        //cc.audioEngine.play(this.audio_fall, false, 1); 
        this.lab_currScoreOver.string = this.currScore.toString();
        var bestScore = localStorage.getItem('bestScore');
        if (bestScore == null) {
            bestScore = this.currScore.toString();
            localStorage.setItem('bestScore', bestScore);
        } else {
            if (parseInt(bestScore) < this.currScore) {
                bestScore = this.currScore.toString();
                localStorage.setItem('bestScore', bestScore)
            }
        }
        this.lab_bestScoreOver.string = '历史最高分：' + bestScore
        this.nodeOver.active = true
        for (let i = 0; i < this.arr_infor.length; i++) {
            if (this.arr_infor[i].name == '我') {
                var bestScore = localStorage.getItem('bestScore');
                this.arr_infor[i].score = parseInt(bestScore);
            }
        }
        this.setPhOver()
    }

    pdCreateBlock() {
        var children = this.node.getChildByName("block").children
        for (let i = children.length - 1; i >= 0; i--) {
            var js = children[i].getComponent(Block)
            if (js) {
                if (js.isPZ) {
                    this.cleanBlock()
                    this.pdDir()
                }
                return
            }
        }
    }

    compare(property: any) {
        return function (a, b) {
            var value1 = a[property];
            var value2 = b[property];
            return value2 - value1;
        }
    }

    addItem(num: any) {
        this.itemParent.removeAllChildren()
        for (let i = 0; i < this.arr_infor.length; i++) {
            if (this.arr_infor[i].name == '我') {
                var bestScore = localStorage.getItem('bestScore')
                if (bestScore == null) {
                    bestScore = "0";
                    localStorage.setItem('bestScore', bestScore)
                } else {
                    bestScore = localStorage.getItem('bestScore')
                }
                this.arr_infor[i].score = parseInt(bestScore)
            }
        }
        this.arr_infor.sort(this.compare('score'))
        console.log(this.arr_infor)
        var item = instantiate(this.pre_item)
        var itemH = item.height
        this.itemParent.height = itemH * num
        for (let i = 0; i < num; i++) {
            var item = instantiate(this.pre_item)
            item.parent = this.itemParent
            var js = item.getComponent(Item)
            if (js) {
                var name = this.arr_infor[i].name
                var score = this.arr_infor[i].score
                var touxing = this.arr_infor[i].touXiang
                js.init(i + 1, name, score, touxing)
            }
            item.y = -48 - i * itemH
        }
    }

    setPhOver() {
        var i_mc_wo = 0
        this.arr_infor.sort(this.compare('score'))
        for (let i = 0; i < this.arr_infor.length; i++) {
            if (this.arr_infor[i].name == '我') {
                i_mc_wo = i + 1
                var bestScore = localStorage.getItem('bestScore')
                this.phOver.getChildByName('node_1').getChildByName('label_mingci').getComponent(Label).string = i_mc_wo
                this.phOver.getChildByName('node_1').getChildByName('label_score').getComponent(Label).string = bestScore
                break
            }
        }
        var i_mc_sj = i_mc_wo - 1
        this.phOver.getChildByName('node_2').getChildByName('label_mingci').getComponent(Label).string = i_mc_sj
        this.phOver.getChildByName('node_2').getChildByName('label_score').getComponent(Label).string = this.arr_infor[i_mc_sj - 1].score
        this.phOver.getChildByName('node_2').getChildByName('label_name').getComponent(Label).string = this.arr_infor[i_mc_sj - 1].name
        this.phOver.getChildByName('node_2').getChildByName('sp_tx').getComponent(Sprite).spriteFrame = this.spa_touXiang.getSpriteFrame('tou_' + this.arr_infor[i_mc_sj - 1].touXiang)
        var i_mc_xj = i_mc_wo + 1
        this.phOver.getChildByName('node_3').getChildByName('label_mingci').getComponent(Label).string = i_mc_xj
        this.phOver.getChildByName('node_3').getChildByName('label_score').getComponent(Label).string = this.arr_infor[i_mc_xj - 1].score
        this.phOver.getChildByName('node_3').getChildByName('label_name').getComponent(Label).string = this.arr_infor[i_mc_xj - 1].name
        this.phOver.getChildByName('node_3').getChildByName('sp_tx').getComponent(Sprite).spriteFrame = this.spa_touXiang.getSpriteFrame('tou_' + this.arr_infor[i_mc_xj - 1].touXiang)
    }

    clickBtn(sender: any, str: any) {
        if (str == 'play') {
            console.log('点击了开始按钮');
            this.cleanAllblock();
            this.unschedule(this.callBackHeroJump);
            this.doubleScore = 1;
            this.isTouchStart = false;
            this.currScore = 0;
            this.lab_score.string = this.currScore;
            this.gameType = 1;
            this.nodePlay.active = true;
            this.nodeReady.active = false;
            this.hero.active = true;
            this.hero.zIndex = 4;
            this.setHeroAct(new Vec3(-140, -140));
            this.createBlock(new Vec3(-140, -140), 0, 1);
            this.createBlock(new Vec3(110, 32), 1, 2);
        } else if (str == 'phb') {
            console.log('点击了排行榜按钮');
            this.addItem(50);
            this.nodePHB.active = true;
        } else if (str == 'closePhb') {
            console.log('点击了排行榜关闭按钮');
            this.nodePHB.active = false;
        } else if (str == 'btnRePlay') {//再玩一次 
            this.cleanAllblock();
            this.doubleScore = 1;
            this.nodeOver.active = false;
            this.currScore = 0;
            this.lab_score.string = this.currScore;
            this.gameType = 1;
            this.hero.zIndex = 4;
            this.hero.eulerAngles.z = 0;
            this.setHeroAct(new Vec3(-140, -140));
            this.createBlock(new Vec3(-140, -140), 0, 1);
            this.createBlock(new Vec3(110, 32), 1, 2);
        } else if (str == 'btnphbOver') {//排行榜（over） 
            this.addItem(50);
            this.nodePHB.active = true;
        }
    }

    setHeroAct(pos: any) {
        Tween.stopAllByTarget(this.hero);//this.hero.stopAllActions();
        this.hero.setScale(1, 1, 1); // 重置缩放 this.hero.scale = 1;
        this.hero.setRotationFromEuler(0, 0, 0); // 重置旋转 this.hero.rotation = 0;
        this.hero.getComponent(UITransform).anchorY = 0;
        this.hero.setPosition(new Vec3(pos.x, pos.y + 200));
        console.log(this.hero.position);
        const act_0 = () => {
            this.hero.getComponent(Hero).canTouch = false; // 禁止触摸
        };
        // 定义每一步移动
        const actions = [
            { duration: 0.2, position: new Vec3(pos.x, pos.y - 10, 0) },
            { duration: 0.08, position: new Vec3(pos.x, pos.y + 50, 0) },
            { duration: 0.07, position: new Vec3(pos.x, pos.y - 5, 0) },
            { duration: 0.06, position: new Vec3(pos.x, pos.y + 10, 0) },
            { duration: 0.03, position: new Vec3(pos.x, pos.y, 0) },
        ];
        const act_6 = () => {
            this.hero.getComponent(Hero).canTouch = true; // 恢复触摸
        };
        const tween = new Tween(this.hero)
            .call(act_0); // 执行第一个回调

        for (const action of actions) {
            tween.to(action.duration, { position: action.position });
        }

        tween
            .call(act_6) // 执行最后一个回调
            .start(); // 启动 Tween
    }

    cleanAllblock() {
        var children = this.node.getChildByName("block").children;
        for (let i = children.length - 1; i >= 0; i--) {
            var js = children[i].getComponent(Block);
            if (js) {
                tween(children[i])
                    .stop();
                this.onBlockKilled(children[i]);
            }
        }
    }

    update(dt: any) {
        if (this.isTouchBegin) {
            this.timeTouch++
            if (this.timeTouch >= 400) {
                this.timeTouch = 400
            }
            var numnum = 0
            var children = this.node.getChildByName("block").children
            for (let i = children.length - 1; i >= 0; i--) {
                var js = children[i].getComponent(Block)
                if (js) {
                    numnum++
                    if (numnum == 2) {
                        js.touchBegin(dt)
                    }
                }
            }
        }
    }

    setRandomBgColor() {
        var i_random = Math.floor(Math.random() * 6)
        // var act_1 = cc.tintTo(0.5, this.arrColorBg[i_random].r, this.arrColorBg[i_random].g, this.arrColorBg[i_random].b); //颜色渐变
        //this.bg.runAction(act_1)
        const targetColor = new Color(this.arrColorBg[i_random].r, this.arrColorBg[i_random].g, this.arrColorBg[i_random].b);
        tween(this.bg)
            .to(0.5, { color: targetColor })
            .start();

    }

    //准备设置
    setReady() {
        this.hero.active = true
        this.hero_2.active = false
        this.hero.zIndex = 4
        this.setHeroAct(new Vec3(-140, -140))
        this.createBlock(new Vec3(-140, -140), 0, 1)
        this.createBlock(new Vec3(110, 32), 1, 2)
        this.callBackHeroJump = function () {
            this.herojunmReady()
        }
        this.schedule(this.callBackHeroJump, 3)
    }

    //hero跳跃准备设置
    herojunmReady() {
        var pos_blockEnd = new Vec3(0, 0)
        var children = this.node.getChildByName("block").children;
        for (let i = children.length - 1; i >= 0; i--) {
            var js = children[i].getComponent(Block);
            if (js) {
                pos_blockEnd = js.pos_dianWorld;
                break;
            }
        }
        var pos_hero = this.hero.getPosition();
        console.log(pos_hero);
        var pos_end = new Vec3(pos_blockEnd.x, pos_blockEnd.y + this.hero.getComponent(UITransform).height / 2);
        var pos_1 = pos_blockEnd.subtract(pos_hero).normalize();
        var act_0 = () => {
            this.hero.getComponent(UITransform).anchorY = 0.5
            this.hero.position = new Vec3(pos_blockEnd.x, pos_blockEnd.y - this.hero.getComponent(UITransform).height / 2);
            console.log(this.hero.position);
        }
        var act_1 = tween(this.hero)
            .to(0.4, {
                position: pos_end, // 移动到目标位置
                easing: 'sineInOut' // 使用合适的缓动函数模拟平滑运动
            });

        var act_2 = tween(this.hero)
            .to(0.4, {
                rotation: this.hero.eulerAngles.z + 360
            });

        var act_3 = tween(this.hero)
            .to(0.4, {
                rotation: this.hero.eulerAngles.z - 360
            });
        var act_4 = ()=>{
            this.hero.getComponent(UITransform).anchorY = 0;

            //this.hero.position = pos_end;
            this.hero.position = new Vec3(pos_end.x, pos_end.y - this.hero.getComponent(UITransform).height / 2);
            console.log(this.hero.position);
            this.cleanBlock();
            this.pdDir();
        }
        if (pos_1.x > 0) {
            var act_5 = tween().parallel(act_1, act_2);
            tween(this.node)
                .call(act_0)
                .then(act_5)
                .call(act_4)
                .start();
        } else {
            var act_6 = tween().parallel(act_1, act_3);
            tween(this.node)
                .call(act_0)
                .then(act_6)
                .call(act_4)
                .start();
        }
    }

    setInfor() {
        // this.arrColorBg = [ 
        // {r:191,g:192,b:201}, 
        // {r:244,g:220,b:216}, 
        // {r:198,g:224,b:211}, 
        // {r:242,g:215,b:171}, 
        // {r:165,g:191,b:216}, 
        // {r:231,g:219,b:222}, 
        // ] 
        // this.arr_infor = [ 
        // {name:'2504549300',touXiang:0,score:1003}, 
        // {name:'cocoscreator_666',touXiang:1,score:1002}, 
        // {name:'我',touXiang:2,score:1001}, 
        // {name:'褪了色旳回憶',touXiang:3,score:Math.round(Math.random() * 1000)}, 
        // {name:'为爱控',touXiang:4,score:Math.round(Math.random() * 1000)}, 
        // {name:'等尽歌悲欢',touXiang:5,score:Math.round(Math.random() * 1000)}, 
        // {name:'妖媚＠',touXiang:6,score:Math.round(Math.random() * 1000)}, 
        // {name:'时光あ瘦了~',touXiang:7,score:Math.round(Math.random() * 1000)}, 
        // {name:'别格式化',touXiang:8,score:Math.round(Math.random() * 1000)}, 
        // {name:'同餐伴枕',touXiang:9,score:Math.round(Math.random() * 1000)}, 
        // {name:'曾有↘几人',touXiang:10,score:Math.round(Math.random() * 1000)}, 
        // {name:'柠檬味的鱼',touXiang:11,score:Math.round(Math.random() * 1000)}, 
        // {name:'没有范儿',touXiang:12,score:Math.round(Math.random() * 1000)}, 
        // {name:'自然而然',touXiang:13,score:Math.round(Math.random() * 1000)}, 
        // {name:'亲，我没跑',touXiang:14,score:Math.round(Math.random() * 1000)}, 
        // {name:'主音King',touXiang:15,score:Math.round(Math.random() * 1000)}, 
        // {name:'名钻',touXiang:16,score:Math.round(Math.random() * 1000)}, 
        // {name:'莫再执迷不悟。',touXiang:17,score:Math.round(Math.random() * 1000)}, 
        // {name:'多啦呮諟個夢',touXiang:18,score:Math.round(Math.random() * 1000)}, 
        // {name:'大哥大@',touXiang:19,score:Math.round(Math.random() * 1000)}, 
        // {name:'女人本该霸气',touXiang:20,score:Math.round(Math.random() * 500)}, 
        // {name:'喓浭喓姒氺溫柔',touXiang:21,score:Math.round(Math.random() * 500)}, 
        // {name:'回忆刺穿心脏╮',touXiang:22,score:Math.round(Math.random() * 500)}, 
        // {name:'爷丶有特点',touXiang:23,score:0}, 
        // {name:'感谢经历。',touXiang:24,score:Math.round(Math.random() * 500)}, 
        // {name:'疾风魔影',touXiang:25,score:Math.round(Math.random() * 500)}, 
        // {name:'坚强的爱恋',touXiang:26,score:Math.round(Math.random() * 500)}, 
        // {name:'路还长别猖狂',touXiang:27,score:Math.round(Math.random() * 500)}, 
        // {name:'余生梦断',touXiang:28,score:Math.round(Math.random() * 500)}, 
        // {name:'笑话太过',touXiang:29,score:Math.round(Math.random() * 500)}, 
        // {name:'白龙吟',touXiang:30,score:Math.round(Math.random() * 500)}, 
        // {name:'心底青苔',touXiang:31,score:Math.round(Math.random() * 500)}, 
        // {name:'独立于世',touXiang:32,score:Math.round(Math.random() * 500)}, 
        // {name:'mo_虚冇',touXiang:33,score:Math.round(Math.random() * 500)}, 
        // {name:'无所谓的结局',touXiang:34,score:Math.round(Math.random() * 500)}, 
        // {name:'半夜成仙',touXiang:35,score:Math.round(Math.random() * 500)}, 
        // {name:'完了丶然后@',touXiang:36,score:Math.round(Math.random() * 500)}, 
        // {name:'没爱没恨-',touXiang:37,score:Math.round(Math.random() * 100)}, 
        // {name:'凉纪之城',touXiang:38,score:Math.round(Math.random() * 110)}, 
        // {name:'梦如南筏〞',touXiang:39,score:Math.round(Math.random() * 100)}, 
        // {name:'-夲亼光锟',touXiang:40,score:Math.round(Math.random() * 100)}, 
        // {name:'褐色眼眸~',touXiang:41,score:Math.round(Math.random() * 100)}, 
        // {name:'太坚强是软弱',touXiang:42,score:Math.round(Math.random() * 100)}, 
        // {name:'暮色伊人',touXiang:43,score:Math.round(Math.random() * 100)}, 
        // {name:'不必谁懂我',touXiang:44,score:Math.round(Math.random() * 100)}, 
        // {name:'嫩HEI炮@!',touXiang:45,score:Math.round(Math.random() * 100)}, 
        // {name:'奈河桥等你',touXiang:46,score:Math.round(Math.random() * 100)}, 
        // {name:'一舞驚鴻',touXiang:47,score:Math.round(Math.random() * 100)}, 
        // {name:'三五七年',touXiang:48,score:Math.round(Math.random() * 100)}, 
        // {name:'冰落風嘯',touXiang:49,score:Math.round(Math.random() * 10)}, 
        // ]; 
    }

}